<?php

require_once (dirname(__FILE__) . '/../models/UserService.php');

class LoginController extends Controller {

	public $layout = "//layouts/main-website";
	private $userService = null;

	public function __construct($id, $module = null) {
		parent::__construct($id, $module);
		$this->userService = new UserService();
	}

	public function actionVerify() {
		if(!isset($_POST["user"])){
			JSONHelper::echoJSON(false);
		}
		$loginform = $_POST["user"];
		//先进行特殊情况判断，企业管理员登陆
		if (isset($loginform["usertype"]) && $loginform["usertype"] == 1) {
			$identity = new UserIdentity($loginform["username"], $loginform["password"]);
			$identity->company_admin_authenticate();
			if ($identity->errorCode === UserIdentity::ERROR_NONE) {
				Yii::app()->user->login($identity);
				Yii::app()->user->setCompanyId($identity->getCompanyId());
				$ret["usertype"] = 1;
				JSONHelper::echoJSON(TRUE, $ret);
			}
		} else {
			$result = $this->userService->verify($_POST, true);
			if (is_int($result)) {
				JSONHelper::echoJSON(false, $result);
			}
			$identity = new UserIdentity($loginform["username"], $loginform["password"]);
			$identity->setId($result["userid"]);
			//$duration=$this->rememberMe?3600*24*30 : 0; // 30 days
			Yii::app()->user->login($identity);
			Yii::app()->user->setUserInfo($result);
		}
		$ret["usertype"] = 0;
		$ret["info"] = $result;
		JSONHelper::echoJSON(true, $ret);
	}

	public function actionLogout() {
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

	/**
	 * user['username'] user['password']
	 * 1 quick login
	 * params username password
	 *
	 * 2 examination resrevation
	 * params
	 *
	 * step 1:if login post set					list or error
	 * step 2:if logined						list
	 * step 3:if not logined and not post set	error
	 *
	 */
	public function actionQiuckLogin() {
		if (isset($_POST['user'])) {
			$user = $_POST["user"];
			$user_ser_ins = new UserService();
			$ret = $user_ser_ins->verify($_POST);
			if (is_array($ret) !== false) {
				Yii::app()->session['user_info'] = $ret;
				Yii::app()->session['user_n_p'] = $user;
				//			echo json_encode("welcome".$ret['name']);
				$this->render('list');
				return;
			} else {
				$this->render("error", array("message" => "错误"));
				return;
			}
		}

		if (isset(Yii::app()->session['user_n_p'])) {
			$user_ser_ins = new UserService();
			$ret = $user_ser_ins->verify(Yii::app()->session['user_n_p']);
			if (is_array($ret) !== false) {
				$this->render('list');
				exit();
			} else {
				$this->render("error", array("message" => "错误"));
				exit();
			}
		}
		$this->render("error", array("message" => "错误"));
	}

	/**
	 * login page
	 * 1. if the user has logined and not cancenllation
	 * return to the main page
	 * 2. if the user's username or password is not right
	 * otherwise
	 *
	 * step 1:if logined							mainpage
	 * step 2:if not logined yet,login post set		login and mainpage
	 * 		  if not logined yet,post not set		mainpage
	 */
	public function actionLogin() {
		if (isset(Yii::app()->session['user_n_p'])) {
			$this->redirect("index.php?r=main/index");
			return;
		}
		if (isset($_POST['user']) && !isset(Yii::app()->session['user_n_p'])) {
			$user = $_POST["user"];
			$user_ser_ins = new UserService();
			$ret = $user_ser_ins->verify($_POST);
			if (is_array($ret) !== false) {
				Yii::app()->session['user_info'] = $ret;
				Yii::app()->session['user_n_p'] = $user;
				$this->redirect("index.php?r=main/index");
				return;
			} else {
				$this->render("error", array("message" => "错误"));
				return;
			}
		} else {
			$this->redirect("index.php?r=main/index");
			return;
		}

		$this->render("error");
	}

	public function actionReserveList() {
		if (isset(Yii::app()->session['user_n_p'])) {
			$this->render('list');
		} else {
			$this->render("error", array("message" => "请先登录"));
		}
	}

	/**
	 *
	 * Enter description here ...
	 */
	public function actionRegisterVerify(){
		$user = $_POST['user'];

		$item = $_POST['registeritem'];
		switch ($item){
			case 'name':
				if (!isset($user['name'])||$user['name'] == ""){
					echo json_encode(array("result" => "姓名必须填写"));
					return;
				}
				return;
			case 'idcard':
				//检查身份证号码
				$id_card = trim($user["idcard"]);
				if (!preg_match('/^(\d{18,18}|\d{15,15}|\d{17,17}x)$/', $id_card)) {
					echo json_encode(array("result" => "身份证号码格式不对"));
					return ;
				}

				//检测身份证号是否重复
				$identity_repeat = B2bUser::model()->findByAttributes(array("identity_no" => $id_card));
				if ($identity_repeat !== null) {
					echo json_encode(array("result" => "身份证号重复"));
					return ;
				}
				return;
			case 'telephone':
				//检测手机号格式是否合法
				if (!preg_match("/1[3-8]\d{9}$/", $user['telephone'])) {
					echo json_encode(array("result" => "检测手机号格式是否合法"));
					return;
				}
				//检测手机号是否重复
				$B2bUser = new B2bUser();
				$telephoneRepeat = $B2bUser->checkPhoneRepeat($user['telephone']);
				if (!$telephoneRepeat) {
					echo json_encode(array("result" => "手机号重复"));
					return ;
				}
				return;
			case 'password':
				if (!isset($user["password"])||$user['password'] == "") {
					echo json_encode(array("result" => "密码没有设置"));
				}
				return;
			case 'repassword':
				if (!isset($user["repassword"])||$user['repassword'] == "") {
					echo json_encode(array("result" => "重复密码没有填写"));
					return;
				}
				if ($user["password"] != $user["repassword"]) {
					echo json_encode(array("result" => "密码与确认密码不同"));
					return;
				}
				return;
			case 'email':
				//检测email是否合法
				$email = trim($user["email"]);
				if (!preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $email)) {
					echo json_encode(array("result" => "email不合法"));
					return;
				}
				//				//检测email是否重复
				$a = $user["email"];
				$b2buser_ins = new B2bUser();
				$mailRepeat = $b2buser_ins->checkEmailRepeat($a);

				if (!$mailRepeat) {
					echo json_encode(array("result" => "email重复"));
					return;
				}
		}
	}

	/**
	 *
	 * Enter description here ...
	 */
	public function actionRegister() {
		$user = $_POST['user'];
		if (!isset($user["password"])) {
			$this->render("registerresult", array("result" => "the password is not site"));
			return;
		}
		if (!isset($user["repassword"])) {
			$this->render("registerresult", array("result" => "the repassword is not site"));
			return;
		}
		if ($user["password"] != $user["repassword"]) {
			$this->render("registerresult", array("result" => "the password is not same"));
			return;
		}
			
		$user["password"] = trim($user["password"]);
		$user_ser_ins = new UserService();
		$arr = array("user" => $user);
		$ret = $user_ser_ins->register($arr);
		//非法请求
		if ($ret == 400) {
			$this->render("registerresult", array("result" => "非法请求"));
			return;
		}

		//检测手机号格式是否合法
		if ($ret == 401) {
			$this->render("registerresult", array("result" => "检测手机号格式是否合法"));
			return;
		}

		//检查身份证号码
		if ($ret == 406) {
			$this->render("registerresult", array("result" => "检查身份证号码"));
			return;
		}

		//检测email是否合法
		if ($ret == 403) {
			$this->render("registerresult", array("result" => "检测email是否合法"));
			return;
		}

		//检测手机号是否重复
		if ($ret == 402) {
			$this->render("registerresult", array("result" => "检测手机号是否重复"));
			return;
		}

		//检测email是否重复
		if ($ret == 404) {
			$this->render("registerresult", array("result" => "检测email是否重复"));
			return;
		}
		//检测身份证号是否重复
		if ($ret == 418) {
			$this->render("registerresult", array("result" => "检测身份证号是否重复"));
			return;
		}

		//成功
		if (is_array($ret)) {
			//			$this->render("registerresult", array("result" => "成功"));
			echo JSONHelper::echoJSON(true, "成功");
			return;
		}
	}

	public function actionIndex() {
                $session = Yii::app()->session;
                $session['item_id'] = '0';
                $this->render("index");
	}

	public function actionPageRegister(){ 
                $session = Yii::app()->session;
                $session['item_id'] = '5';
		$this->render("register");
	}


	public function actionPageEnroll(){
                $session = Yii::app()->session;
                $session['item_id'] = '6';
		$this->render("enroll");
	}

	public function actionPageRetrieve() {
		$this->render("retrieve");
	}
	/**
	 * get new password
	 * Enter description here ...
	 */
	public function actionRetrieve() {
		$user = $_POST['user'];

		if (!preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $user['email'])) {
			JSONHelper::echoJSON(false, "邮箱格式不对");
		}
		if (!isset($_POST['verification'])||$_POST['verification'] == "验证码"){
			JSONHelper::echoJSON(false, "没有填写验证码");
		}
		session_start();
		if ($_POST['verification'] != $_SESSION['check_gd']){
			JSONHelper::echoJSON(false, "验证码填写错误");
		}
		
		$user_servie = new UserService();
		$ret = $user_servie->getPassword($user);
		if ($ret === 400) {
			JSONHelper::echoJSON(false, "非法请求");
			exit();
		}
		if ($ret === 419) {
			JSONHelper::echoJSON(false, "找到不到此邮箱");
			exit();
		}
		if ($ret === 421) {
			JSONHelper::echoJSON(false, "发送邮件异常");
			exit();
		}
		if ($ret === 420) {
			//			$this->render("getparesult", array("result" => "发送邮件失败", "status" => 0));
			JSONHelper::echoJSON(false, "发送邮件失败");
			exit();
		}
		//if the verification is not exit
		//		//if the verification is not right
		JSONHelper::echoJSON(false, "成功发送");
	}

	public function actionNewPaPage() {
		$this->render("getnewpa");
	}

	public function actionGdcheck(){
		/*
		 * 生成图片验证码
		 * and open the template in the editor.
		 */
		session_start();
		$rand ='';
		for($i=0;$i<4;$i++){
			$rand.=dechex(rand(1,15)); //生成4位数包含十六进制的随机数
		}
		$_SESSION['check_gd']=$rand;
		$img=imagecreatetruecolor(100,30); //创建图片
		$bg=imagecolorallocate($img,0,0,0); //第一次生成的是背景颜色
		$fc=imagecolorallocate($img,255,255,255); //生成的字体颜色
		//给图片画线
		for($i=0;$i<3;$i++){
			$te=imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));
			imageline($img,rand(0,15),0,100,30,$te);
		}
		//给图片画点
		for($i=0;$i<200;$i++){
			$te=imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255));
			imagesetpixel($img,rand()%100,rand()%30,$te);
		}
		//首先要将文字转换成utf-8格式
		//$str=iconv("gb2312","utf-8","呵呵呵");
		//加入中文的验证
		//smkai.ttf是一个字体文件，为了在别人的电脑中也能起到字体作用，把文件放到项目的根目录，可以下载，还有本机C:\WINDOWS\Fonts中有
		//		imagettftext($img,11,10,20,20,$fc,"simkai.ttf","你好你好");
		//把字符串写在图片中
		imagestring($img,rand(1,6),rand(3,70),rand(3,16),$rand,$fc);
		//输出图片
		header("Content-type:image/jpeg");
		imagejpeg($img);
		//		$this->render("error",array("ret" => imagejpeg($img)));
	}
}